package kontrol;

import view.ViewOverview;

/**
 *
 * @author kagioglu
 */
public class OverviewManager
{
    private final ViewOverview overview;
    private final String name;
    private final String[] legend;
    private final HasList thing;

    private boolean isOverviewOpen;
    private boolean isQueueOpen;
    private HasQueue[] list;
    private int index;
    private String[] listStrings;
    private String[] queueStrings;

    public OverviewManager
    (
        ViewOverview overview,
        String name,
        String[] legend,
        HasList thing
    )
    {
        this.overview = overview;
        this.name = name;
        this.legend = legend;
        this.thing = thing;
        this.isOverviewOpen = false;
        this.isQueueOpen = false;
        this.index = 0;
    }
    
    public void incrementSelection()
    {
        this.updateIndex(this.index + 1);
    }
    
    public void decrementSelection()
    {
        this.updateIndex(this.index - 1);
    }

    private void updateIndex( int newindex )
    {
        int size = this.listStrings.length;
        if(size > 0)
        {
            this.index = (newindex + size) % size;
            this.overview.setSelectionIndex(this.index);
            this.queueStrings = this.list[this.index].getQueue();
        }
    }
    
    public void toggleQueue()
    {
        if(this.isOverviewOpen)
        {
            if(this.isQueueOpen)
            {
                this.overview.closeCommandQueue();
            }
            else
            {
                this.overview.openCommandQueue(this.queueStrings);
            }
            this.isQueueOpen = !this.isQueueOpen;
        }
    }
    
    public void openOverview()
    {
        if(!this.isOverviewOpen)
        {
            this.recalculate();
            this.overview.openOverview(this.name, this.listStrings, this.legend);
            this.isOverviewOpen = true;
        }
    }
    
    public void closeOverview()
    {
        if(this.isOverviewOpen)
        {
            if(this.isQueueOpen) this.overview.closeCommandQueue();
            this.overview.closeOverview();
            this.isOverviewOpen = false;
        }
    }
    
    private void recalculate()
    {
        this.list = this.thing.getHasQueues();
        this.listStrings = new String[this.list.length];
        for(int i = 0; i < this.list.length; i++)
        {
            this.listStrings[i] = this.list[i].getName();
        }
        this.updateIndex(this.index);
    }

    public void refresh()
    {
        this.recalculate();
        if(this.isOverviewOpen) this.overview.setOverview(this.listStrings);
        if(this.isQueueOpen) this.overview.setCommandQueue(this.queueStrings);
    }
}
